const moment = require("moment");
const McMeeting = require('./db/mc_meeting')
const McMeetingUserRelation = require('./db/mc_meeting_user_relation')
const User = require('./db/user')
const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from "@agconnect/common-server"

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

let myHandler = async function (event, context, callback, logger) {
  // const start = Date.now()
  const { userId, status, startTime, endTime, pageNum = 1, pageSize = 10 } = event.body ? JSON.parse(event.body) : event
  logger.info("userId: " + userId + ", status: " + status + ", startTime: " + startTime + ", endTime: " + endTime + ", pageNum: " + pageNum + ", pageSize: " + pageSize)
  // 获取当前用户信息
  const userQuery = clouddb.CloudDBZoneQuery.where(User.user).equalTo("id", userId)
  const respUserInfo = await mCloudDBZone.executeQuery(userQuery)
  const userInfo = respUserInfo.getSnapshotObjects()
  // logger.info("1:", Date.now() - start)


  // 先查询自身的会议列表， 按照状态跟时间
  let meetingCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeeting.mc_meeting)
  meetingCloudDBZoneQuery.equalTo("createBy", userId)
    .lessThanOrEqualTo("startTime", moment(endTime, "YYYY/MM/DD HH:mm:ss").toDate())
    .greaterThanOrEqualTo("startTime", moment(startTime, "YYYY/MM/DD HH:mm:ss").toDate())
    .in("status", status)
    .orderByAsc("startTime")
    .limit(pageSize * pageNum - 1, (pageNum - 1) * pageSize)
  const respMeeting = await mCloudDBZone.executeQuery(meetingCloudDBZoneQuery)
  const meetingData = respMeeting.getSnapshotObjects()
  // logger.info("2:", Date.now() - start)
  // 查出对应会议的用户列表
  if (meetingData?.length) {
    // 先查出当前会议的参与用户
    let cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeetingUserRelation.mc_meeting_user_relation)
    cloudDBZoneQuery.in("meetingId", meetingData.map(r => r.id))
    const respUser = await mCloudDBZone.executeQuery(cloudDBZoneQuery);
    const relationData = respUser.getSnapshotObjects()
    if (relationData?.length) {
      // 在通过用户id列表获取用户信息
      const userQuery = clouddb.CloudDBZoneQuery.where(User.user).in('id', relationData.map(item => item.userId))
      const respUserInfo = await mCloudDBZone.executeQuery(userQuery)
      const userList = respUserInfo.getSnapshotObjects()

      const userObjects = userList.reduce((acc, item) => {
        acc[item.id] = item
        return acc
      }, {})

      const relationObjects = relationData.reduce((acc, item) => {
        if(acc[item.meetingId]) {
          acc[item.meetingId].push(userObjects[item.userId])
        } else {
          acc[item.meetingId] = [userObjects[item.userId]]
        }

        return acc
      }, {})

      meetingData.forEach(item => {
        // const users = relationData.filter(li => li.meetingId == item.id).map(item => item.userId)
        // if (users?.length) {
        //   item.relationUsers = userList.filter(li => users.includes(li.id))
        // }
        if(relationObjects[item.meetingId]) {
          item.relationUsers = relationObjects[item.meetingId]
        }
      })
    }
    // logger.info("3:", Date.now() - start)

    meetingData.forEach(item => {
      item.relationUsers = [...userInfo, ...(item.relationUsers || [])]
    })
  }
  let inMeetingData = []
  if (status.includes(1) || status.includes(2)) {
    // 然后查询这个用户参与了哪些会议, 只有结束跟正在进行中才需要
    let cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeetingUserRelation.mc_meeting_user_relation)
    cloudDBZoneQuery.equalTo("userId", userId)
      .lessThanOrEqualTo("startTime", moment(endTime, "YYYY/MM/DD HH:mm:ss").toDate())
      .greaterThanOrEqualTo("startTime", moment(startTime, "YYYY/MM/DD HH:mm:ss").toDate())
    const respUser = await mCloudDBZone.executeQuery(cloudDBZoneQuery);
    if (respUser) {
      const relationData = respUser.getSnapshotObjects()
      if (relationData?.length) {
        let meetingIds = relationData.map(item => item.meetingId)
        // 查到参与的会议列表之后，查询对应的状态会议以及排序
        let participateInCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeeting.mc_meeting)
        participateInCloudDBZoneQuery.in("id", meetingIds).in("status", status).orderByAsc("startTime")
        const respParticipateIn = await mCloudDBZone.executeQuery(participateInCloudDBZoneQuery);
        inMeetingData = respParticipateIn.getSnapshotObjects()
      }
    }
  }
  // logger.info("4:", Date.now() - start)



  let res = new context.HTTPResponse({
    code: 200,
    msg: '成功',
    data: {
      meetingData,
      inMeetingData
    }
  }, {
    "faas-content-type": "json"
  }, "application/json", "200");
  callback(res);
};

export { myHandler };